require 'fileutils'
class ProjectsController < ApplicationController
  layout "company",:except=>[:set_manager,:set_employee,:deliver_chart,:ms,:desc]
  before_filter :check_authentication,:set_session,:except=>[:deliver_chart,:desc]
  #in_place_edit_for :project,:name
  def set_session
    Thread.current[:user] = @cur_user
    Thread.current[:role] = session[:role]
  end

  # GETs should be safe (see http://www.w3.org/2001/tag/doc/whenToUseGet.html)
  #verify :method => :post, :only => [  :create ],
  #       :redirect_to => { :action => :list }

  def index
      @act = params[:act]
      if pid = params[:id]
	  project = Project.find(pid)
	  logger.info("===="+project.completed.to_s+"==================")
	  if project.completed.to_s == "Yes"
	    project.completed = "No"
	  else 
	    project.completed = "Yes"
	  end
	  project.save
      end
      @company = @cur_user.company.reload
      @user  = @cur_user
      @users = @company.users
      @plan = @company.plan
      @project = Project.new
      if params[:tab].to_s == "show_all_projects"
      @project_pages, @projects= paginate :projects, :per_page => 10,:conditions=>["company_id = ?",@cur_user.company.id],:order => "id desc"
      elsif params[:tab].to_s == "show_completed_projects"
      @project_pages, @projects= paginate :projects, :per_page => 10,:conditions=>["company_id = ? AND id IN (SELECT id FROM projects WHERE completed = 'Yes')",@user.company.id],:order => "id desc"
      else
      @project_pages, @projects= paginate :projects, :per_page => 10,:conditions=>["company_id = ? AND id IN (SELECT id FROM projects WHERE completed = 'No' or completed IS NULL)",@cur_user.company.id],:order => "id desc"
      end
	render :partial=>'project'  if @page == 1 or request.post?
  end
  #projects list for modalbox
  def modal
     if @cur_user.account_owner? or @cur_user.global_user?
       @projects = @cur_user.company.active_projects 
     else
       @projects = @cur_user.active_projects    
     end
      render :layout=>'modal'
  end
  def desc
     @project = Project.find(params[:pid])
  end

  def show_active_projects
	@project = Project.new
	@user = @cur_user
	@company = @user.company.reload
	@users = @company.users
	@plan = @company.plan
    @project_pages, @projects= paginate :projects, :per_page => 10,:conditions=>["company_id = ? AND id IN (SELECT id FROM projects WHERE completed = 'No' or completed is NULL)",@user.company.id],:order => "id desc"
	render :partial=>'project'  if @page == 1 or request.post?
  end
  def show_completed_projects
	@project = Project.new
	@user = @cur_user
	@company = @user.company.reload
	@users = @company.users
	@plan = @company.plan
    @project_pages, @projects= paginate :projects, :per_page => 10,:conditions=>["company_id = ? AND id IN (SELECT id FROM projects WHERE completed = 'Yes')",@user.company.id],:order => "id desc"
	render :partial=>'project'  if @page == 1 or request.post?
  end

  def show_all_projects
	@company = @cur_user.company.reload
	@user = @cur_user
	@users = @company.users
	@project = Project.new
	@plan = @company.plan
    @project_pages, @projects= paginate :projects, :per_page => 10,:conditions=>["company_id = ?",@cur_user.company.id],:order => "id desc"
	render :partial=>'project'  if @page == 1 or request.post?
  end

  def show
    @project = Project.find(params[:id])
	@users = @project.users
	@user = @cur_user
    @data = "<graph yAxisMaxValue='1' xAxisName='" + "Activities".t + "' caption='" + "Project Overview".t + "' baseFontSize='12' outCnvBaseFont='ms shell dlg'>"
    @data = @data + "<set value='#{@project.users.size}' color='CC0000' name='" + "Users".t + "'/>"
    @data = @data + "<set value='#{@project.messages.size}' color='AFD8F8' name='" + "Message".t + "'/>"
    @data = @data + "<vLine dashed='1' dashLen='2' dashGap='2'/>"
    @data = @data + "<set value='#{@project.todos.size}' color='F6BD0F' name='" + "Todo".t + "'/>"
    @data = @data + "<set value='#{@project.writeboards.size}' color='EEDDFF' name='" + "Writeboards".t + "'/>"
    @data = @data + "</graph>"
    respond_to do |format|
      format.html #show.rhtml
      format.xml {render :xml => @project.to_xml}
    end
  end

  def show_all_users
    @project = Project.find(params[:id])
	@users = @project.users
	@user = @cur_user
    @time_log_pages, @time_logs = paginate :time_logs, :per_page => 10,:conditions=>["project_id = ?",@project.id],:order => "id desc"
	render :partial=>'time_logs/time_log' if @page == 1 or request.post?
  end

  def new
    @project = Project.new
    @users = @cur_user.children
  end

  def create
        @project = Project.new(params[:project])
	@project.add_at = Time.now
	@user = @cur_user
	@user.company.projects << @project
	@company = @user.company
	@save = @project.save
	@plan = @company.plan

        #relate users with projects
	if params[:user_ids]
	params[:user_ids].each do |u|
	  task = Task.new
	  task.project = @project
	  task.user_id = u
	  task.save
	end
	end

        #PART I
        #clone roles
	@company.roles.each do |role|
	  prj_role = Role.new
	  prj_role.identifier = role.identifier
	  prj_role.project_id = @project.id
	  prj_role.save
	end

        #PART II 
        #clone default categories;
        msg_cats = @company.msg_categories.sort_by(&:id)
        msg_cats.each do |cat|
          ncat = Category.new
          ncat.project = @project
          ncat.name    = cat.name
          ncat.label = 'msg'
          ncat.save
        end

        wb_cats = @company.wb_categories.sort_by(&:id)
        wb_cats.each do |cat|
          ncat = Category.new
          ncat.project = @project
          ncat.name    = cat.name
          ncat.label = 'writeboards'
          ncat.save
        end

        fs_cats = @company.file_categories.sort_by(&:id)
        fs_cats.each do |cat|
          ncat = Category.new
          ncat.project = @project
          ncat.name    = cat.name
          ncat.label = 'files'
          ncat.save
        end

	#PART III 
        #create default permissions to project

        #STEP 1
	#add view permission to all roles	
        prj_per_view = StaticPermission.new
        prj_per_view.identifier = 'prj_' + @project.id.to_s + "_parent_view"
	prj_per_view.save
	#add to all roles
        @project.roles.each do |prj_role|
	  prj_role.static_permissions << prj_per_view
	end

        #STEP 2
	#clone default permissions
        sps = StaticPermission.find(:all,:conditions=>"identifier like 'com_#{@project.company.id}_%'")
	sps.each do |sp|
	  #2.1 replace com identifier to prj identifier
	  sp_split = sp.identifier.split("_")

	  if sp.identifier.match("msg_cat") 
	    cat_id = sp_split[2]
	    if cat_id == "unc"
              prj_idr = "prj_" + @project.id.to_s + "_" + sp.identifier.split("com_#{@project.company.id}_").last
	    else
	      next if Category.find_by_id(cat_id.to_i).nil?
	      prj_cat_id = @project.msg_categories[@company.msg_categories.index(Category.find(cat_id))].id
              prj_idr = "prj_" + @project.id.to_s + "_" + prj_cat_id.to_s + "_msg_cat_" + sp.identifier.split("_msg_cat_").last
	    end
	  elsif sp.identifier.match("wb_cat")
	    cat_id = sp_split[2]
	    if cat_id == "unc"
              prj_idr = "prj_" + @project.id.to_s + "_" + sp.identifier.split("com_#{@project.company.id}_").last
	    else
	      next if Category.find_by_id(cat_id.to_i).nil?
	      prj_cat_id = @project.wb_categories[@company.wb_categories.index(Category.find(cat_id))].id
              prj_idr = "prj_" + @project.id.to_s + "_" + prj_cat_id.to_s + "_wb_cat_" + sp.identifier.split("_wb_cat_").last
	    end
	  elsif sp.identifier.match("fs_cat")
	    cat_id = sp_split[2]
	    if cat_id == "unc"
              prj_idr = "prj_" + @project.id.to_s + "_" + sp.identifier.split("com_#{@project.company.id}_").last
	    else
	      next if Category.find_by_id(cat_id.to_i).nil?
	      prj_cat_id = @project.file_categories[@company.file_categories.index(Category.find(cat_id))].id
              prj_idr = "prj_" + @project.id.to_s + "_" + prj_cat_id.to_s + "_fs_cat_" + sp.identifier.split("_fs_cat_").last
	    end
	  else
            prj_idr = "prj_" + @project.id.to_s + "_" + sp.identifier.split("com_#{@project.company.id}_").last
	  end

          #to see if exist
          prj_per = StaticPermission.find_by_identifier(prj_idr)
          #create a new
          if prj_per.nil?
             prj_per = StaticPermission.new
             prj_per.identifier = prj_idr
             prj_per.save
          end
          logger.error prj_per

          #with each role of this permission, add prj permission
	  sp.roles.each do |role| 
	   if role.identifier.match("custom")
	     role.static_permissions << prj_per
	   else
	     @project.roles[@company.roles.index(role)].static_permissions << prj_per
	   end
          end #sp
         end #sps
        
        #PART II 
        #inherit clone
        npis = NoPermissionInherit.find(:all,:conditions=>"company_id = #{@project.company.id} and identifier not like '%_cat_%'")
        npis.each do |npi|
          prj_npi = NoPermissionInherit.new
          prj_npi.project_id = @project.id
          prj_npi.identifier = "prj_" + @project.id.to_s + "_" + npi.identifier.split("com_#{@project.company.id}_").last
          prj_npi.save
        end

	#msg category inherit clone
        npi_msg = NoPermissionInherit.find(:all,:conditions=>"identifier like 'com_#{@project.company.id}_%_cat'")
	npi_msg.each do |np|
	    npary = np.identifier.split("_")
	    cat_id = npary[2]
	    type = npary[3]
	  if cat_id == "unc" or (cat_id.to_i > 0 and (not Category.find_by_id(cat_id.to_i).nil?))
	    if cat_id == "unc"
              prj_idr = "prj_" + @project.id.to_s + "_#{cat_id}_#{type}_cat"
	    else
	      if type == "msg"
	        prj_cat_id = @project.msg_categories[@company.msg_categories.index(Category.find(cat_id))].id
              elsif type == "wb"
	        prj_cat_id = @project.wb_categories[@company.wb_categories.index(Category.find(cat_id))].id
              else
	        prj_cat_id = @project.file_categories[@company.file_categories.index(Category.find(cat_id))].id
	      end
              prj_idr = "prj_" + @project.id.to_s + "_" + prj_cat_id.to_s + "_#{type}_cat"
	    end
	  #create no permission
          prj_npi = NoPermissionInherit.new
          prj_npi.project_id = @project.id
          prj_npi.identifier = prj_idr
          prj_npi.save
	  end
        end



        @project_pages, @projects = paginate :projects, :per_page => 10,:conditions=>["company_id = ? AND id IN (SELECT id FROM projects WHERE completed = 'No' or completed IS NULL)",@user.company.id],:order => "id desc"
	id = @project.id
	render :update do |page|
	  page.hide 'indicator_create'
	  page.hide 'new_project'
	  page << "$('sub_create').disabled = false"
	  page.replace_html 'projects_list', :partial=>'project'
	  page.visual_effect :highlight, 'entry_' + id.to_s, :duration=>4.5
	end
  end

  def edit
    @project = Project.find(params[:id])
	@users = @cur_user.company.users
  end

  def update
    @project = Project.find(params[:id])
    if @project.update_attributes(params[:project])
      flash[:notice] = 'Project was successfully updated.'
	 @project.tasks.each do |t|
	   t.destroy
	 end
	if params[:user_ids]
	 params[:user_ids].each do |u|
	  task = Task.new
	  task.project = @project
	  task.user_id = u
	  task.save
	 end
	end
      redirect_to projects_path()
    else
      render :action => 'edit'
    end
  end

  def destroy
    project = Project.find(params[:id])
    #destroy project milestones
    logger.error("--destroy project messages---------------")
    project.messages.each {|m| m.destroy}
    logger.error("--destroy project messages---------------")
    project.msg_categories.each {|m| m.destroy}
    logger.error("--destroy project milestones---------------")
    project.milestones.each {|m| m.destroy}
    logger.error("---destroy project todos---------------")
    project.todos.each do |todo|
      todo.todo_items.each {|ti| ti.destroy}
      todo.destroy
    end
    logger.error("---destroy project times---------------")
    project.time_logs.each {|t| t.destroy}
    logger.error("---destroy project files---------------")
    project.files.each {|f| f.destroy}
    logger.error("---destroy project dir ---------------")
     FileUtils.remove_dir("#{RAILS_ROOT}/public/files/#{project.id}") if File.exist?("#{RAILS_ROOT}/public/files/#{project.id}")
    #destroy project
    project.destroy
    @user = @cur_user
    @project = Project.new
    @company = @user.company
    @plan = @company.plan
    @project_pages, @projects= paginate :projects, :per_page => 10,:conditions=>["company_id = ? AND id IN (SELECT id FROM projects WHERE completed = 'No' or completed IS NULL)",@user.company.id],:order => "id desc"
	render :update do |page|
	  page.replace_html 'projects_list',:partial => "project"
	end
  end

  def set_manager
  if session[:role] == nil
	session[:role] = Hash.new
  end
    role = session[:role]
    role[params[:id]] = "m"	
    logger.error("==============set manager======")
	logger.error(role.to_s)
    logger.error("==============set manager======")
  end

  def set_employee
    role = session[:role]
	role[params[:id]] = "e"
    logger.error("==============set employee======")
	logger.error(role.to_s)
    logger.error("==============set employee======")
  end
  def update_activity
    id = params[:id]
    name = params[:name]
	actvt = ActivityType.find(id)
	actvt.name = name
	actvt.save
    render :update do |page|
	 page.replace_html 'activity_types', :partial=>'activity_type'
	end
  end

  #generate chart xml
  def deliver_chart
    #@headers["Content-Type"] = "application/xml;charset=UTF-8" 
    @project = Project.find(params[:project_id])
    @data = gantt_data(@project)
    respond_to do |format|
      format.html
      format.xml {
       render :layout => false
      }
    end
  end
  def ms
    #@headers["Content-Type"] = "application/xml;charset=UTF-8" 
    @data = gantt_data(@project)
  end

  #finish project
  def finish
      if pid = params[:id]
         project = Project.find(pid)
	  logger.info("===="+project.completed.to_s+"==================")
	  if project.completed.to_s == "Yes"
	    project.completed = "No"
	  else 
	    project.completed = "Yes"
	  end
	  project.save
      end
      @company = @cur_user.company.reload
      @user  = @cur_user
      @users = @company.users
      @plan = @company.plan
      @project = Project.new
      if project.completed == "Yes"
      @tab = 2
      logger.error("-------------------------" + @tab.to_s)
      @project_pages, @projects= paginate :projects, :per_page => 10,:conditions=>["company_id = ? AND id IN (SELECT id FROM projects WHERE completed = 'Yes')",@cur_user.company.id],:order => "id desc"
      else
      @tab = 1
      logger.error("-------------------------" + @tab.to_s)
      @project_pages, @projects= paginate :projects, :per_page => 10,:conditions=>["company_id = ? AND id IN (SELECT id FROM projects WHERE completed = 'No' or completed IS NULL)",@cur_user.company.id],:order => "id desc"
      end
     render :update do |page|
       page.replace_html 'projects_list', :partial=>'project' 
       page.visual_effect :highlight,'entry_' + pid.to_s,:duration => 5
     end
  end
end












